package ve.gob.cne.dao;

import java.io.Serializable;



import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;


public class GenericDao extends HibernateDaoSupport implements Dao {


	public GenericDao() {
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see ve.gob.cne.dao.Dao#persist(java.lang.Object)
	 * 
	 * Metodo que se encarga de guardar o actualizar un objeto
	 */

	@Transactional
	public void persist(Object entity) {
		getHibernateTemplate().saveOrUpdate(entity);
		getHibernateTemplate().flush();
	}
	
	/*
	 * (non-Javadoc)
	 * @see ve.gob.cne.dao.Dao#persist(java.lang.Object[])
	 * 
	 * Metodo que se encarga de guardar o actualizar varios objetos
	 * 
	 */

	@Transactional
	public void persist(Object[] entities) {
		for (int i = 0; i < entities.length; i++) {
			persist(entities[i]);
		}
		getHibernateTemplate().flush();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public <T> List<T> find(Class<T> entityClass) {
		final List<T> entities = getHibernateTemplate().loadAll(entityClass);
		return entities;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public <T> T load(Class<T> entityClass, Serializable id) {
		final T entity = (T)getHibernateTemplate().load(entityClass, id);
		return entity;
		
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public <T> List<T> find(String hql) {
		final List<T> entities = getHibernateTemplate().find(hql);
		return entities;
		
	}
	
	@Transactional
	public void remove(Object entity) {
        	getHibernateTemplate().delete(entity);     
        	getHibernateTemplate().flush();
    }
	
	@Transactional
	public <T> void deleteAll(Collection<T> entities) {
        getHibernateTemplate().deleteAll(entities);
        getHibernateTemplate().flush();
    }
	
	@Transactional
	public <T> void deleteAll(Class<T> entityClass) {
		deleteAll(find(entityClass));
    }
	
	public Session getObjectSession(){
		return getSession();
	}

}
